﻿using System.Collections.Concurrent;
using System.Net.WebSockets;

namespace StudyCompanion.Commons.WebSocket;

public class WebSocketConnectionManager
{
    private readonly ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> _sockets = new();

    public int GetCount()
    {
        return _sockets.Count;
    }

    public System.Net.WebSockets.WebSocket GetSocketById(string id)
    {
        return _sockets.FirstOrDefault(p => p.Key == id).Value;
    }

    public ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> GetAll()
    {
        return _sockets;
    }

    public System.Net.WebSockets.WebSocket GetWebSocket(string key)
    {
        System.Net.WebSockets.WebSocket _socket;
        _sockets.TryGetValue(key, out _socket);
        return _socket;
    }

    public string GetId(System.Net.WebSockets.WebSocket socket)
    {
        return _sockets.FirstOrDefault(p => p.Value == socket).Key;
    }

    public void AddSocket(System.Net.WebSockets.WebSocket socket, string key)
    {
        if (GetWebSocket(key) != null) _sockets.TryRemove(key, out var destoryWebsocket);
        _sockets.TryAdd(key, socket);
        //string sId = CreateConnectionId();
        //while (!_sockets.TryAdd(sId, socket))
        //{
        //    sId = CreateConnectionId();
        //}
    }

    public async Task RemoveSocket(string id)
    {
        try
        {
            System.Net.WebSockets.WebSocket socket;

            _sockets.TryRemove(id, out socket);


            await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
        }
        catch (Exception)
        {
        }
    }

    public async Task CloseSocket(System.Net.WebSockets.WebSocket socket)
    {
        await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
    }

    private string CreateConnectionId()
    {
        return Guid.NewGuid().ToString();
    }
}